﻿using Microsoft.Extensions.DependencyInjection;

namespace 初识依赖注入
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建服务集合
            var services = new ServiceCollection();
            // 注册服务
            services.AddTransient<Test1>();
            services.AddTransient<Test2>();
            // 构建服务提供者
            using (var serviceProvider = services.BuildServiceProvider())
            {
                ITest testInstance = serviceProvider.GetService<Test1>();   //和GetRequiredService有什么区别？ 
                testInstance.SayHi();
                testInstance = serviceProvider.GetRequiredService<Test2>();
                testInstance.SayHi();
            }
            Console.WriteLine("Hello, World!");
        }
    }

    interface ITest
    {
        public string Name { get; set; }
        void SayHi();
    }

    class Test1 : ITest
    {
        public string Name { get; set; } = "初识依赖注入";
        public void SayHi()
        {
            Console.WriteLine($"Hi, I am {Name} from Test1");
        }
    }

    class Test2 : ITest
    {
        public string Name { get; set; } = "依赖注入示例";
        public void SayHi()
        {
            Console.WriteLine($"Hi, I am {Name} from Test2");
        }
    }
}
